package com.jiang.mall.mallproduct.product.web;

import com.jiang.mall.mallproduct.product.entity.CategoryEntity;
import com.jiang.mall.mallproduct.product.service.CategoryService;
import com.jiang.mall.mallproduct.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //1.查出所有的一級分類
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categories();
        model.addAttribute("categories", categoryEntities);

        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();

        return map;
    }

    /**
     * redission 测试
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        // 这里为什么没有设置过期时间？Redission设置了自动过期时间：30s。
        //     即使加锁后发生异常系统宕机代码不能执行删锁命令，锁自动过期。
        // 业务时间超长使锁过期的现象会不会发生？
        //     看门狗监听业务代码是否执行完毕，没有执行完毕锁过期时会给锁续期
        RLock lock = redissonClient.getLock("lock");
//        lock.lock(); //看门狗会自动以30s的三分之一时间为周期给锁的ttl重新赋上30s
        // 业务主打方法：省去续期操作。设置锁的过期时间超过业务的执行时间
        lock.lock(31, TimeUnit.SECONDS); // 设置过期时间后没有看门狗自动续期
//        lock.lock(10, TimeUnit.SECONDS); // 锁的过期时间小于业务的执行时间，报错
//        java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id
        try {
            System.out.println("加锁成功。。。执行业务");
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            System.out.println("释放锁。。。" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 测试读写锁 -读锁
     * 读读 相当于没上锁
     * 读写 读锁上锁 写锁等待
     * 写读 写锁上锁 读锁等待
     * 写写 肯定上锁且阻塞
     * 写锁-独占锁；互斥锁；排他锁
     * @return
     */
    @ResponseBody
    @GetMapping("/read")
    public String read() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功");
            Thread.sleep(20000);
        } catch (Exception e) {

        } finally {
            System.out.println("读锁释放");
            rLock.unlock();
        }
        return "read";
    }

    /**
     * 测试读写锁 -写锁
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String write() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock rLock = readWriteLock.writeLock();
        rLock.lock();
        try {
            System.out.println("写锁加锁成功");
            Thread.sleep(20000);
        } catch (Exception e) {

        } finally {
            System.out.println("写锁释放");
            rLock.unlock();
        }
        return "write";
    }

    /**
     * 测试信号量 Semaphore
     * 在redis中设置 cart=3
     * 占车位
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/in")
    public String in() throws InterruptedException {
        RSemaphore cart = redissonClient.getSemaphore("cart");
//        cart.acquire(); // 当cart的数量为0时，再去做减法会阻塞等待，直到cart变成了1，这个减法才会做下去，让cart变成最小值 1-》0
        boolean b = cart.tryAcquire();
        return "in ===》" + b;
    }

    /**
     * 释放车位
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/out")
    public String out() throws InterruptedException {
        RSemaphore cart = redissonClient.getSemaphore("cart");
        cart.release();
        return "out";
    }

    /**
     * 测试闭锁
     * 在redis设置countDownLatch=3
     * 访问fangjia方法，页面等待
     * 再访问一次gogogo方法倒计时减一
     * 多次访问直到countDownLatch归零，fangjia方法页面成功跳转，显示“放假”
     */
    @ResponseBody
    @GetMapping("/fangjia")
    public String fangJia() throws InterruptedException {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("countDownLatch");
        countDownLatch.await();
        return "放假了";
    }

    @ResponseBody
    @GetMapping("/gogogo")
    public String gogogo() {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("countDownLatch");
        countDownLatch.countDown();
        return "走了一个";
    }
}
